package com.wytec.xywzxw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.wytec.xywzxw.bean.Account;
import com.wytec.xywzxw.bean.commonBean.PageSizeBean;
import com.wytec.xywzxw.configuration.MyException;
import com.wytec.xywzxw.mapper.AccountMapper;
import com.wytec.xywzxw.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;

    @Override
    public List<Account> getAccountList(PageSizeBean page, String keyword){
        QueryWrapper<Account>queryWrapper =  new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()){
            queryWrapper.like("username",keyword).or().like("mobile",keyword);
        }
        PageHelper.startPage(page.getPage(), page.getSize());
        List<Account> accounts = accountMapper.selectList(queryWrapper);
        return accounts;
    }

    @Override
    public void editAccount(Account account) {
        try {
            accountMapper.updateById(account);
        }catch(Exception e){
            new MyException(e.getMessage());
        }
    }

    @Override
    public void delAccount(Account account) {
        try {
            accountMapper.deleteById(account.getId());
        }catch(Exception e){
            new MyException(e.getMessage());
        }
    }

    @Override
    public Account login(Account loginAccount) {
        QueryWrapper<Account>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",loginAccount.getUsername()).or().eq("mobile",loginAccount.getUsername());
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null){
            new MyException("用户不存在");
        }
        if (!account.getPassword().equals(loginAccount.getPassword())){
            new MyException("密码错误");
        }
        if (account.getStatus() == 0){
            new MyException("账号已被禁用");
        }
        return account;
    }
}
